package com.qlk.odcinterface.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.qlk.odcinterface.domain.PmsCoupon;
import com.qlk.odcinterface.domain.PmsCouponChannel;
import com.qlk.odcinterface.domain.PmsCouponItem;
import com.qlk.odcinterface.domain.query.PmsCouponQuery;
import com.qlk.odcinterface.manager.PmsCouponManager;
import com.qlk.odcinterface.sdk.api.request.OdcRequest;
import com.qlk.odcinterface.sdk.api.request.PmsCouponItemRequest;
import com.qlk.odcinterface.sdk.api.request.PmsCouponRequest;
import com.qlk.odcinterface.service.PmsCouponService;
import com.qlk.odcinterface.utils.bean.BeanUtilsEx;
import com.qlk.odcinterface.utils.exceptions.ExistedException;
import com.qlk.common.utils.StringUtil;
import com.qlk.common.utils.page.PageUtil;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.filter.RequestContextFilter;
import org.perf4j.aop.Profiled;
 
/**
 * PmsCouponService接口的实现类
 * 
 * @author zhaoyanan
 * @version 2016-4-14 14:11:36
 * 
 */
@Service
public class PmsCouponServiceImpl implements PmsCouponService {

    /** LOG */
    private static final Log LOG = LogFactory.getLog(PmsCouponServiceImpl.class);

    @Autowired
    private PmsCouponManager pmsCouponManager;

    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsCouponService.batchInsert")
    public boolean insert(List<PmsCoupon> pmsCouponList) {
        boolean resultFlag = false;
        try {
            if (CollectionUtils.isNotEmpty(pmsCouponList)) {
                resultFlag = pmsCouponManager.insert(pmsCouponList);
            } else {
                LOG.warn("PmsCouponServiceImpl#batchInsert failed, param is illegal.");
            }
        } catch (Exception e) {
            LOG.error("PmsCouponServiceImpl#batchInsert has error.", e);
        }
        return resultFlag;
    }

    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsCouponService.insert")
    public boolean insert(PmsCoupon pmsCoupon) {
        boolean resultFlag = false;
        try {
            if (null != pmsCoupon) {
                if (pmsCouponManager.exist(pmsCoupon)) {
                    throw new ExistedException();
                }
                resultFlag = pmsCouponManager.insert(pmsCoupon);
            } else {
                LOG.warn("PmsCouponServiceImpl#insert failed, param is illegal.");
            }
        } catch (ExistedException e) {
            LOG.warn("PmsCouponServiceImpl#insert failed, pmsCoupon has existed.");
            throw e;
        } catch (Exception e) {
            LOG.error("PmsCouponServiceImpl#insert has error.", e);
        }
        return resultFlag;
    }

    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsCouponService.update")
    public boolean update(PmsCoupon pmsCoupon) {
        boolean resultFlag = false;
        try {
            if (null != pmsCoupon && null != pmsCoupon.getId()) {
                resultFlag = pmsCouponManager.update(pmsCoupon);
            } else {
                LOG.warn("PmsCouponServiceImpl#update failed, param is illegal.");
            }
        } catch (Exception e) {
            LOG.error("PmsCouponServiceImpl#update has error.", e);
        }
        return resultFlag;
    }

    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsCouponService.queryPmsCouponList")
    public List<PmsCoupon> queryPmsCouponList(PmsCouponQuery queryBean) {
        List<PmsCoupon> pmsCouponList = null;
        try {
            pmsCouponList = pmsCouponManager.queryPmsCouponList(queryBean);
        } catch (Exception e) {
            LOG.error("PmsCouponServiceImpl#queryPmsCouponList has error.", e);
        }
        return pmsCouponList;
    }

    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsCouponService.queryPmsCouponListWithPage")
    public List<PmsCoupon> queryPmsCouponListWithPage(PmsCouponQuery queryBean, PageUtil pageUtil) {
        List<PmsCoupon> pmsCouponList = null;
        try {
            pmsCouponList = pmsCouponManager.queryPmsCouponListWithPage(queryBean, pageUtil);
        } catch (Exception e) {
            LOG.error("PmsCouponServiceImpl#queryPmsCouponListWithPage has error.", e);
        }
        return pmsCouponList;
    }

    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsCouponService.delete")
    public boolean delete(PmsCoupon pmsCoupon) {
        boolean resultFlag = false;
        try {
            if (null != pmsCoupon && null != pmsCoupon.getId()) {
                resultFlag = pmsCouponManager.delete(pmsCoupon);
            } else {
                LOG.warn("PmsCouponServiceImpl#delete param is illegal.");
            }
        } catch (Exception e) {
            LOG.error("PmsCouponServiceImpl#delete has error.", e);
        }
        return resultFlag;
    }

    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsCouponService.batchDelete")
    public boolean delete(PmsCoupon[] pmsCoupons) {
        boolean resultFlag = false;
        try {
            if (null != pmsCoupons && pmsCoupons.length > 0) {
                resultFlag = pmsCouponManager.delete(pmsCoupons);
            } else {
                LOG.warn("PmsCouponServiceImpl#batchDelete failed, param is illegal.");
            }
        } catch (Exception e) {
            LOG.error("PmsCouponServiceImpl#batchDelete has error.", e);
        }
        return resultFlag;
    }

    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsCouponService.getPmsCouponById")
    public PmsCoupon getPmsCouponById(Long id) {
        PmsCoupon pmsCoupon = null;
        try {
            if (null != id) {
                pmsCoupon = pmsCouponManager.getPmsCouponById(id);
            } else {
                LOG.warn("PmsCouponServiceImpl#getPmsCouponById failed, param is illegal.");
            }
        } catch (Exception e) {
            LOG.error("PmsCouponServiceImpl#getPmsCouponById has error.", e);
        }
        return pmsCoupon;
    }
    
    /**
     * {@inheritDoc}
     */
    @Profiled(tag = "PmsCouponService.syncPmsCoupon")
	public boolean syncPmsCoupon(Integer isStatusUpdate,PmsCouponRequest couponRequest,Integer preStatus) {
		boolean resultFlag = false;
		try{
			
			//request 转换 对应 bean
			PmsCoupon pmsCoupon = new PmsCoupon();
			BeanUtils.copyProperties(couponRequest, pmsCoupon);
			
			List<PmsCouponItemRequest> requestItems = couponRequest.getItemList();//优惠券明细
			List<PmsCouponItem> couponItems = new ArrayList<PmsCouponItem>();
			
			//赋值明细中的promotionId
			if(null != requestItems && requestItems.size() > 0){
				PmsCouponItem couponItem = new PmsCouponItem();
				for(PmsCouponItemRequest itemRequest : requestItems){
					couponItem = new PmsCouponItem();
					BeanUtils.copyProperties(itemRequest, couponItem);
					couponItem.setPromotionId(pmsCoupon.getId().intValue());
					couponItems.add(couponItem);
				}
			}
			
			
			//根据优惠券编码查询odc库中优惠券信息
			PmsCouponQuery couponQuery = new PmsCouponQuery();
			couponQuery.setCode(pmsCoupon.getCode());
			List<PmsCoupon> list = pmsCouponManager.queryPmsCouponList(couponQuery);
			
			//渠道转换 及 数据拼装
			List<PmsCouponChannel> channels = convertChannel(couponRequest);
			
			if(null == list || list.size() == 0){//odc中无该数据，执行 insert操作
				
				resultFlag = pmsCouponManager.insertPmsCoupon(couponItems, pmsCoupon, channels);
			}else{//odc中已存在此优惠券信息，执行 update操作
				if(null == isStatusUpdate) {
					LOG.error("更新标识isStatusUpdate为空!");
					return false;
				}
				
				if(0 != isStatusUpdate && 1 != isStatusUpdate && 2 != isStatusUpdate){
					LOG.error("更新标识isStatusUpdate不合法!");
					return false;
				}
				
				if(0 == isStatusUpdate){//整体更新 已存在的odc 优惠券数据
					PmsCoupon oldCoupon = list.get(0);//odc已存在的信息
					resultFlag = pmsCouponManager.updatePmsCoupon(couponItems, pmsCoupon, channels,oldCoupon);
				}
				
				if(1 == isStatusUpdate){//只更新odc库中该编码存在的状态信息
					PmsCoupon oldCoupon = list.get(0);//odc已存在的信息
					if(preStatus != oldCoupon.getStatus()){
						LOG.error("odc已存在状态"+oldCoupon.getStatus()+",pms入参前置状态:"+preStatus);
						throw new Exception("odc优惠券更新异常，前置状态数据异常");
					} 
						
						
					resultFlag = pmsCouponManager.updatePmsCouponStatus(pmsCoupon);
				}
				
				if(2 == isStatusUpdate){//删除odc中优惠券信息
					resultFlag = pmsCouponManager.updateDeleteAt(pmsCoupon);
				}
			}
		}catch(Exception e){
			LOG.error("PmsCouponServiceImpl#addBatch has error.", e);
		}
		return resultFlag;
	}
	
    /**
     * 渠道 转换成对应list
     * @param couponRequest
     * @return
     */
    public List<PmsCouponChannel> convertChannel(PmsCouponRequest couponRequest){
    	String channel = couponRequest.getChannel();
    	if(StringUtils.isEmpty(channel)) return null;
    	
    	List<PmsCouponChannel> channels = new ArrayList<PmsCouponChannel>();
		String[] channelsArr = channel.split(",");
		PmsCouponChannel couponChannel;
		for(String s : channelsArr){
			couponChannel = new PmsCouponChannel();
			couponChannel.setChannelId(Integer.parseInt(s));
			couponChannel.setPromotionId(couponRequest.getId().intValue());
			channels.add(couponChannel);
		}
			
		return channels;
    }
}

